/**
 * 公用的表单组件
 */
import React from 'react';
import { Form } from 'antd';
import classNames from 'classnames';
import { FormComponentProps } from 'antd/es/form';
import connectFn from '@/utils/connectFn';
import CreateDrawer from '@/components/CreateDrawer';
import { StateType } from '@/common-typings';
// import { types, getFormatDate } from '@/utils/utils';
import { assignDefaultFormData, filterFormData } from '@/components/Common/utils';
import { Selector } from './Selector';
import './index.less';

export interface FormConfigProps {
  config: any[]; // 表单配置项
  rules?: any[]; // 表单校验规则
  layout?: string; // 表单布局
  className?: string;
  isPopup?: boolean; // 是否为modal中的表单
  formItemLayout?: any; // 表单子项布局方式
  requestList?: Function; // 表单提交回掉方法
  [propName: string]: any;
}

interface CreateFormProps {
  formConfig: FormConfigProps;
  form: FormComponentProps['form'];
  [propName: string]: any;
}

// const createFormField = (value: any) => Form.createFormField({ value });

@connectFn([{ global: ['isMobile'] }])
@CreateDrawer
class CreateForm extends React.PureComponent<CreateFormProps> {
  formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 4 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 20 },
    },
  };

  /**
   * 点击查询，重置，确定等按钮时的回掉方法，并且对表单数据进行整理
   * @param key
   * @param callback 回掉方法
   */
  beforeSearchCallBack = (key: string, callback?: Function) => {
    const { formConfig, beforeCloseCallBack, closeDrawer, form }: any = this.props;
    let params = assignDefaultFormData(this.props);
    // 重置按钮，清空数据以及校验
    if (key === 'reset') {
      form.resetFields();
      formConfig.requestList(params, key);

      // 如果是弹窗
    } else if (formConfig.isPopup) {
      form.validateFields((error: any) => {
        if (!error) {
          beforeCloseCallBack('confirm');
        }
      });

      // 如果是查询或者导出
    } else if (key === 'submit' || key === 'export') {
      form.validateFields((error: any, value: {}) => {
        if (!error) {
          // 获取表单最初当默认参数, 只获取hidden item的value
          params = assignDefaultFormData(this.props, true);

          filterFormData(value, formConfig);

          // 将默认参数和Form参数合并
          params = Object.assign({}, params, value);
          if (callback) {
            callback(params);
          } else {
            formConfig.requestList(params, key);
          }
        }
      });

      // 如过不是以上场景，回掉参数
    } else if (callback) {
      callback(params);
    }

    // 移动端关闭表单弹出层回调
    if (closeDrawer) closeDrawer();
  };

  /**
   * 渲染formItem
   * @param item
   * @param formConfig
   */
  renderFormItem(item: StateType, formConfig: StateType) {
    return Selector(item, formConfig, this);
  }

  /**
   * 渲染formGroup
   */
  renderFormGroup() {
    const { formConfig } = this.props;
    if (formConfig.config) {
      return formConfig.config.map((item: StateType) => {
        // 排除formItem中隐藏项
        if (item.options.hidden) {
          return '';
        }
        return this.renderFormItem(item, formConfig);
      });
    }
    return null;
  }

  render() {
    const { formConfig, isMobile } = this.props;

    // 如果有配置，采用传递的布局
    let formItemLayout = formConfig.formItemLayout || {};
    // 当为弹窗时，若无配置，采用默认的布局
    if (formConfig.isPopup) {
      formItemLayout = formConfig.formItemLayout || this.formItemLayout;
    }

    return (
      <div
        className={classNames(
          'st-form',
          formConfig.isPopup ? 'st-form-pop' : '',
          isMobile && !formConfig.noDrawer ? 'st-form-drawer' : '',
        )}
        style={formConfig.style || { paddingBottom: '20px' }}
      >
        <Form
          layout={formConfig.layout || (isMobile && !formConfig.noDrawer ? 'vertical' : 'inline')}
          onSubmit={this.beforeSearchCallBack}
          {...formItemLayout}
        >
          {this.renderFormGroup()}
        </Form>
      </div>
    );
  }
}

export default Form.create<CreateFormProps>({ name: 'create-form' })(CreateForm);
